package cn.sfrog.project.biz.web.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.core.controller.BaseController;
import cn.sfrog.common.core.domain.AjaxResult;
import cn.sfrog.common.core.domain.ApiAjaxResult;
import cn.sfrog.common.core.domain.entity.SysDictData;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.enums.AgreementTypeEnum;
import cn.sfrog.common.obs.HwObsUtil;
import cn.sfrog.common.oss.OssProperties;
import cn.sfrog.common.oss.service.OssTemplate;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.common.utils.bean.BeanUtils;
import cn.sfrog.common.utils.file.FileUploadUtils;
import cn.sfrog.project.biz.admin.service.IBizDepartmentService;
import cn.sfrog.project.biz.admin.service.IBizHospitalService;
import cn.sfrog.project.biz.web.vo.AppGroupCityQueryVO;
import cn.sfrog.project.biz.web.vo.index.AppDepartmentResultVO;
import cn.sfrog.project.biz.web.vo.index.AppHospitalVO;
import cn.sfrog.project.biz.web.vo.index.AppProfessionalVO;
import cn.sfrog.system.domain.SysAgreementConf;
import cn.sfrog.system.domain.SysAppVersion;
import cn.sfrog.system.domain.vo.app.AppCityGroupLetterVO;
import cn.sfrog.system.domain.vo.app.AppCityLetterListVO;
import cn.sfrog.system.service.ISysAgreementConfService;
import cn.sfrog.system.service.ISysAppVersionService;
import cn.sfrog.system.service.ISysCityService;
import cn.sfrog.system.service.ISysDictDataService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/common")
@Api(value = "/api/common", tags = "APP通用相关")
public class AppCommonController extends BaseController {
    @Autowired
    private ISysAgreementConfService sysAgreementConfService;


    @Autowired
    private OssProperties ossProperties;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysCityService sysCityService;
    @Autowired
    private ISysAppVersionService appVersionService;
    @Autowired
    private IBizHospitalService bizHospitalService;
    @Autowired
    private IBizDepartmentService bizDepartmentService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 获取隐私协议|服务政策|关于我们
     * @param type
     * @return
     */
    @ApiOperation(value = "获取隐私协议|用户端服务政策|陪诊医生端服务政策|关于我们|充值协议",httpMethod = "GET")
    @GetMapping("/getAgreement/{type}")
    public ApiAjaxResult agreement(@PathVariable AgreementTypeEnum type){
        SysAgreementConf agreementConf = sysAgreementConfService.getOne(Wrappers.lambdaQuery(SysAgreementConf.class).eq(SysAgreementConf::getContentType, type));
        if(StringUtils.isNull(agreementConf)){
            return ApiAjaxResult.success("");
        }
        return ApiAjaxResult.success("查询成功",agreementConf.getContent());
    }


    /**
     * 通用文件上传
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "上传文件", httpMethod = "POST")
    @PostMapping("/uploadFile")
    public AjaxResult uploadFileOSS(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        String uploadFileUrl = "";
        File tempFile;
        try {
            if(multipartFile == null){
                return AjaxResult.error("文件上传失败");
            }
            // 文件后缀
            String suffix = "."+ FileUploadUtils.getExtension(multipartFile);
            // 临时文件
            tempFile = File.createTempFile("tmp", suffix);
            multipartFile.transferTo(tempFile);
            uploadFileUrl =  HwObsUtil.uploadFile(tempFile);
            tempFile.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> resultMap = new HashMap<>(2);
        resultMap.put("url", uploadFileUrl);
        return AjaxResult.success(resultMap);
    }


    @ApiOperation(value = "查询所有城市【首字母分组】")
    @GetMapping("/groupByCityLetter")
    public AjaxResult groupByCityLetter(@Valid AppGroupCityQueryVO queryVO){
        List<AppCityGroupLetterVO> data = new ArrayList<>();
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(queryVO.getKeywords())){
            data = redisCache.getCacheList(Constants.GROUP_LETTER_CITY);
            if(CollUtil.isNotEmpty(data)){
                return AjaxResult.success(data);
            }
        }
        List<AppCityLetterListVO> cityList = sysCityService.groupByCityLetter(queryVO.getKeywords());
        cityList.forEach(e -> {
            e.setLetter(PinyinUtil.getFirstLetter(e.getName(),"").toUpperCase(Locale.ROOT).substring(0,1));
        });
        Map<String, List<AppCityLetterListVO>> collect = cityList.stream().collect(Collectors.groupingBy(AppCityLetterListVO::getLetter));
        data = new ArrayList<>();
        for (Map.Entry<String, List<AppCityLetterListVO>> entry : collect.entrySet()) {
            data.add(new AppCityGroupLetterVO(entry.getKey(),entry.getValue()));
        }
        if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isBlank(queryVO.getKeywords())){
            redisCache.setCacheList(Constants.GROUP_LETTER_CITY,data);
        }
        return AjaxResult.success(data);
    }

    @ApiOperation(value = "获取APP最新版本")
    @GetMapping("/getAppVersion/{type}")
    public ApiAjaxResult<SysAppVersion> getAppLatestVersion(@ApiParam(name = "type",value = "填写android或ios")@PathVariable String type ){
       SysAppVersion version =  appVersionService.selectAppLatestVersion(type);
       return ApiAjaxResult.success(version);

    }

    @ApiOperation(value = "获取所有医院")
    @GetMapping("/getAllHospitalList")
    public ApiAjaxResult<List<AppHospitalVO>> getAllHospitalList(){
       List<AppHospitalVO> hospitalList =  bizHospitalService.selectAppAllHospitalList();
       return ApiAjaxResult.success(hospitalList);
    }

    @ApiOperation(value = "获取医院下所有科室")
    @GetMapping("/getDepartmentList/{hospitalId}")
    public ApiAjaxResult<List<AppDepartmentResultVO>> getDepartmentList(@PathVariable("hospitalId") Long hospitalId){
        List<AppDepartmentResultVO> appDepartmentResultVOS = bizDepartmentService.selectAppDepartmentListByHospitalId(hospitalId);
        return ApiAjaxResult.success(appDepartmentResultVOS);
    }

    @ApiOperation(value = "获取陪诊|护工|医生认证职业名称列表",httpMethod = "GET")
    @GetMapping("/getProfessional/{type}")
    public ApiAjaxResult<List<AppProfessionalVO>> getProfessional(@PathVariable("type") @ApiParam(name = "type",value = "类型【escort=陪诊 care_worker=护工 doctor=医生】") String type){
        SysDictData sysDictData = new SysDictData();
        if("escort".equals(type)){
            sysDictData.setDictType("escort_level");
        }else if("care_worker".equals(type)){
            sysDictData.setDictType("biz_care_worker_level");
        }else if("doctor".equals(type)){
            sysDictData.setDictType("biz_doctor_title");
        }
        List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictData);
        List<AppProfessionalVO> appProfessionalVOS = BeanUtils.convertList2List(sysDictDataList, AppProfessionalVO.class);
        return ApiAjaxResult.success(appProfessionalVOS);
    }


}
